package net.wanho.async;

import cn.hutool.system.SystemUtil;
import eu.bitwalker.useragentutils.UserAgent;
import net.wanho.mapper.sys.LogininforMapper;
import net.wanho.po.sys.Logininfor;
import net.wanho.util.AddressUtils;
import net.wanho.util.SpringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.TimerTask;

public class AsyncTask {

    public static TimerTask recordLogininfor(final HttpServletRequest req,final String userName,final String msg,final String status ) {

        // 主体
        final Subject subject = SecurityUtils.getSubject();
        // 浏览器名称
        final String browserName = UserAgent.parseUserAgentString(req.getHeader("User-Agent")).getBrowser().getName();

        // 登录日志的线程任务
        return new TimerTask() {
            @Override
            public void run() {
                Logininfor logininfor = new Logininfor();
                logininfor.setUserName(userName);
                logininfor.setIpaddr(subject.getSession().getHost());
                logininfor.setLoginLocation(AddressUtils.getRealAddressById(SystemUtil.getHostInfo().getAddress()));
                logininfor.setBrowser(browserName);
                logininfor.setOs(SystemUtil.getOsInfo().getName());
                logininfor.setStatus(status);
                logininfor.setMsg(msg);
                logininfor.setLoginTime(new Date());
                // 从spring环境中获取LogininforMapper对象，这里注入不了LogininforMapper，因为不是Spring创建此对象
                LogininforMapper logininforMapper = SpringUtils.getBean(LogininforMapper.class);
                logininforMapper.insertLogininfor(logininfor);
            }
        };

    }
}
